package com.trendata.util;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.trendata.domain.User;

/**
 * 微信
 * 
 * @author: HuangXiuXiu Email:243559392@qq.com
 */
public class WeChatUtil {

	private static Logger logger = Logger.getLogger("wechatLogger");

	/**
	 * 获取接口访问凭证
	 * 
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 */
	public static String getAccessToken() {
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constants.APP_ID + "&secret="
				+ Constants.APP_SECRET;
		// 发起GET请求获取凭证
		JSONObject jsonObject = HttpClientUtil.httpsRequest(requestUrl, "GET", null);
		String accessToken = "";
		if (null != jsonObject) {
			try {
				accessToken = jsonObject.getString("access_token");
				return accessToken;
			} catch (JSONException e) {
				logger.error("获取accessToken出现异常:" + e.getMessage() + "，jsonObejct:" + jsonObject.toString());
			}
		}
		return null;
	}

	/**
	 * 获取jsapi_ticket
	 * 
	 * @param accessToken
	 * @return
	 */
	public static String getJSTicket(String accessToken) {
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
		JSONObject jsonObject = HttpClientUtil.httpsRequest(requestUrl, "GET", null);
		try {
			String jsTicket = jsonObject.getString("ticket");
			return jsTicket;
		} catch (Exception e) {
			logger.error("获取微信jsTicket时jsonObject转换出现异常：" + e.getMessage() + "，jsonObject内容为:" + jsonObject.toString());
		}
		return null;
	}

	/**
	 * 获取用户基本信息（包括UnionID机制） </br> 开发者可通过OpenID来获取用户基本信息。使用https协议。
	 * 
	 * @param accessToken
	 *            调用接口凭证。必须
	 * @param openId
	 *            普通用户的标识，对当前公众号唯一。必须
	 * @return ResultDO<User>
	 */
	public static ResultDO<User> getUser(String accessToken, String openId) {
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
		JSONObject jsonObject = HttpClientUtil.httpsRequest(requestUrl, "GET", null);
		ResultDO<User> resultDO = new ResultDO<User>();
		User user = null;
		if (jsonObject != null) {
			user = new User();
			try {
				user.setSubscribe(Boolean.valueOf(jsonObject.getString("subscribe")));
				user.setOpenId(openId);
				user.setNickName(jsonObject.getString("nickname"));
				user.setSex(jsonObject.getInt("sex"));
				user.setLanguage(jsonObject.getString("language"));
				user.setCountry(jsonObject.getString("country"));
				user.setProvince(jsonObject.getString("province"));
				user.setCity(jsonObject.getString("city"));
				user.setHeadImgUrl(jsonObject.getString("headimgurl"));
				user.setSubscribeTime(jsonObject.getLong("subscribe_time"));
				resultDO.setModule(user);
				resultDO.setSuccess(true);
			} catch (JSONException e) {
				logger.error("通过openId:" + openId + "获取微信用户信息时jsonObject转换出现异常：" + e.getMessage() + "，jsonObject内容为:"
						+ jsonObject.toString());
				if (jsonObject.get("errcode") != null) {
					resultDO.setErrCode(jsonObject.getString("errcode"));
				}
				if (jsonObject.get("errmsg") != null) {
					resultDO.setErrMsg(jsonObject.getString("errmsg"));
				}
			}
		}
		return resultDO;
	}

	/**
	 * 永久二维码请求
	 * 
	 * @param accessToken
	 * @param shopOpenId
	 * @return
	 */
	public static ResultDO<Map<String, String>> createQRCode(String accessToken, long shopOpenId) {
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
		String outputStr = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + shopOpenId + "}}}";
		JSONObject jsonObject = HttpClientUtil.httpsRequest(requestUrl, "POST", outputStr);
		ResultDO<Map<String, String>> resultDO = new ResultDO<Map<String, String>>();
		if (jsonObject != null) {
			try {
				String url = jsonObject.getString("url");
				String ticket = jsonObject.getString("ticket");
				Map<String, String> map = new HashMap<String, String>();
				map.put("url", url);
				map.put("ticket", ticket);
				resultDO.setModule(map);
				resultDO.setSuccess(true);
			} catch (Exception e) {
				if (jsonObject.get("errcode") != null) {
					resultDO.setErrCode(jsonObject.getString("errcode"));
				}
				if (jsonObject.get("errmsg") != null) {
					resultDO.setErrCode(jsonObject.getString("errmsg"));
				}
			}
		}
		return resultDO;
	}

	/**
	 * 通过ticket换取二维码
	 * 
	 * @param ticket
	 * @return
	 */
	public static HttpsURLConnection showQRCode(String ticket) {
		HttpsURLConnection conn = null;
		try {
			String requestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLDecoder.decode(ticket, "utf-8");
			conn = HttpClientUtil.httpsRequest(requestUrl, "GET");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

}
